// pages/buy/buy.js
const cloud = wx.cloud;
cloud.init({
    env: cloud.DYNAMIC_CURRENT_ENV
})
// 获取数据库引用
const db = cloud.database();
Page({
    data: {
        goodsInfo: {}, // 商品信息
        addressInfo: {}, // 收货地址信息
        orderInfo: {
            goodsTotalPrice: 0,
            shippingFee: 0,
            remarks: '',
            totalPrice: 0
        }, // 订单信息
        isSubmitting: false, // 提交中状态
        hasAddress: false, // 是否有收货地址
        selectedAddressId: 0
    },

    onLoad(options) {
        // 存储回调函数到全局
        getApp().addressSelectCallback = (addressId) => {
            this.getAddressDetail(addressId);
        };
        // 从商品详情页传递过来的商品ID
        const {
            goodsId,
            goodsInfo
        } = options;
        if (options.goodsId) {
            this.setData({
                goodsId: options.goodsId,
                goodsInfo: JSON.parse(options.goodsInfo)
            });
            // 计算订单信息
            this.calculateOrderInfo();
        } else {
            wx.showToast({
                title: '参数错误',
                icon: 'none',
                success: () => {
                    setTimeout(() => {
                        wx.navigateBack();
                    }, 1500);
                }
            });
        }

        // 获取默认收货地址
        this.getDefaultAddress();
    },
    onShow() {
        // 如果有选中的地址ID，获取地址详情
        if (this.data.selectedAddressId) {
            this.getAddressDetail(this.data.selectedAddressId);
        }
    },
    getAddressDetail(addressId) {
        wx.showLoading({
            title: '加载中...',
        });

        // 调用云函数获取地址详情
        wx.cloud.callFunction({
            name: 'address',
            data: {
                action: 'detail',
                userId: wx.getStorageSync('userInfo')._id,
                addressId: addressId
            }
        }).then(res => {
            wx.hideLoading();

            if (res.result.success) {
                this.setData({
                    addressInfo: res.result.address,
                    hasAddress: true
                });
            } else {
                wx.showToast({
                    title: res.result.message || '获取地址失败',
                    icon: 'none'
                });
            }
        }).catch(err => {
            wx.hideLoading();
            console.error('获取地址详情失败:', err);
            wx.showToast({
                title: '获取地址失败，请重试',
                icon: 'none'
            });
        });
    },
    // 获取默认收货地址
    getDefaultAddress() {
        wx.showLoading({
            title: '加载中...',
            mask: true
        });

        // 获取当前用户ID
        const userId = wx.getStorageSync('userInfo._id');

        // 调用云函数获取默认地址
        wx.cloud.callFunction({
            name: 'address',
            data: {
                action: 'getDefault',
                userId: wx.getStorageSync('userInfo')._id,
            }
        }).then(res => {
            console.log(res);
            wx.hideLoading();
            if (res.result.success && res.result.address) {
                this.setData({
                    addressInfo: res.result.address,
                    hasAddress: true
                });
            } else {
                this.setData({
                    hasAddress: false
                });
                // 没有地址，提示用户添加
                wx.showToast({
                    title: '请添加收货地址',
                    icon: 'none'
                });
            }
        }).catch(err => {
            wx.hideLoading();
            console.error('获取默认地址失败:', err);
            this.setData({
                hasAddress: false
            });
            wx.showToast({
                title: '获取地址失败，请重试',
                icon: 'none'
            });
        });
    },

    // 计算订单信息
    calculateOrderInfo() {
        const {
            goodsInfo
        } = this.data;
        console.log(goodsInfo);
        // 计算商品总价
        const goodsTotalPrice = goodsInfo.goodsPrice;
        //计算运费
        const shippingFee = goodsInfo.shippingFee
        // 计算实付款
        const totalPrice = goodsTotalPrice + shippingFee;

        this.setData({
            orderInfo: {
                goodsTotalPrice: goodsTotalPrice.toFixed(2),
                shippingFee: shippingFee.toFixed(2),
                totalPrice: totalPrice.toFixed(2),
                remarks: ''
            }
        });
    },

    // 选择收货地址
    selectAddress() {
        console.log(this.data.addressInfo);
        let selectedAddressId = this.data.addressInfo._id
        wx.navigateTo({
            url: `/pages/addressList/addressList?isFromSelect=true&selectedAddressId=${selectedAddressId}`
        });
    },
    // 备注
    bindTextAreaBlur(e) {
        this.setData({
            'orderInfo.remarks': e.detail.value
        })
    },
    // 提交订单
    submitOrder() {
        // 检查是否有收货地址
        if (!this.data.hasAddress) {
            wx.showToast({
                title: '请选择收货地址',
                icon: 'none'
            });
            return;
        }

        // 设置提交中状态
        this.setData({
            isSubmitting: true
        });

        const {
            goodsInfo,
            addressInfo,
            orderInfo
        } = this.data;
        console.log(goodsInfo);
        console.log(addressInfo);
        console.log(orderInfo);
        wx.showLoading({
            title: '加载中...',
        });
        // 调用云函数创建订单
        wx.cloud.callFunction({
            // 云函数名称
            name: 'wxpayFunctions',
            data: {
                // 调用云函数中的下单方法
                type: 'wxpay_order',
                data: {
                    goodsId: goodsInfo._id,
                    goodsName: goodsInfo.goodsName,
                    price: orderInfo.totalPrice,
                    count: 1,
                    addressId: addressInfo._id,
                    sellerId:goodsInfo.sellerId,
                    buyerId:wx.getStorageSync('userInfo')._id,
                    remarks:orderInfo.remarks
                }
            },
        }).then(res => {
            console.log('下单结果: ', res);
            wx.hideLoading()
            this.setData({
                isSubmitting: false
            });
            const orderId = res.result.orderId
            const paymentData = res.result.paymentParams;
            console.log(paymentData);
            // 唤起微信支付组件，完成支付
            wx.requestPayment({
                timeStamp: paymentData?.timeStamp,
                nonceStr: paymentData?.nonceStr,
                package: paymentData?.packageVal,
                paySign: paymentData?.paySign,
                signType: 'RSA', // 该参数为固定值
                success(res) {
                    // 支付成功回调，实现自定义的业务逻辑
                    console.log('唤起支付组件成功：', res);
                    wx.cloud.callFunction({
                        // 云函数名称
                        name: 'payNotify',
                        data: {
                            goodsId: goodsInfo._id,
                        },
                    }).then(res => {
                        console.log(res);
                        wx.navigateTo({
                            url: `/pages/orderSuccess/orderSuccess?orderId=${orderId}`
                        })
                    }).catch(err => {
                        console.error('更新失败', err);
                    })
                },
                fail(err) {
                    
                    // 支付失败回调
                    console.error('唤起支付组件失败：', err);
                    
                    wx.showToast({
                        title: '取消支付',
                        icon: 'none'
                    })
                },
            });
        }).catch(err => {
            wx.hideLoading()
            this.setData({
                isSubmitting: false
            });
            console.error('创建订单失败:', err)
            wx.showToast({
                title: '系统错误，请重试',
                icon: 'none'
            })
        });
    }
})